package src.Sixteen;

import cn.hutool.core.io.resource.ResourceUtil;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.util.Vector;

/**
 * @ClassName Question111
 * @Description
 * @Author keke
 * @Time 2022/6/29 21:07
 * @Version 1.0
 */
public class Question111 {

    public static void main(String[] args) {
        //System.out.println(SwingUtilities.isEventDispatchThread());
        ChatClientFrame client = new ChatClientFrame();
        client.createClientSocket();
    }
}

class ChatClientFrame extends JFrame {

    private static final long serialVersionUID = -2793611581379586611L;
    private JTextArea textAreaInfo;
    private JList<?> userList;
    private JTextField textFieldNewUser;
    private JTextField textFieldSend;
    private ObjectOutputStream outputStream;
    private Socket socket;
    private boolean loginFlag = false;

    public ChatClientFrame() {
        setTitle("聊天室客户端");
        setVisible(true);
        setBounds(100, 100, 385, 288);

        final JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.SOUTH);

        final JLabel label = new JLabel();
        label.setText("输入聊天内容：");
        panel.add(label);

        textFieldSend = new JTextField();
        textFieldSend.addActionListener(e -> send());
        textFieldSend.setPreferredSize(new Dimension(180, 25));
        panel.add(textFieldSend);

        final JButton button = new JButton();
        button.addActionListener(e -> send());
        button.setText("发  送");
        panel.add(button);

        final JSplitPane splitPane = new JSplitPane();
        splitPane.setDividerLocation(100);
        getContentPane().add(splitPane, BorderLayout.CENTER);

        final JScrollPane scrollPane = new JScrollPane();
        splitPane.setRightComponent(scrollPane);

        textAreaInfo = new JTextArea();
        textAreaInfo.setFont(new Font("", Font.BOLD, 14));
        scrollPane.setViewportView(textAreaInfo);

        final JScrollPane scrollPane1 = new JScrollPane();
        splitPane.setLeftComponent(scrollPane1);

        userList = new JList();
        userList.setModel(new DefaultComboBoxModel(new String[] {""}));
        scrollPane1.setViewportView(userList);

        final JPanel panel1 = new JPanel();
        getContentPane().add(panel1, BorderLayout.NORTH);

        final JLabel label1 = new JLabel();
        label1.setText("用户名称：");
        panel1.add(label1);

        textFieldNewUser = new JTextField();
        textFieldNewUser.setPreferredSize(new Dimension(140, 25));
        panel1.add(textFieldNewUser);

        final JButton button1 = new JButton();
        button1.addActionListener(e -> {
            if (loginFlag) {
                JOptionPane.showMessageDialog(null, "在同一窗口只能登录一次。");
                return;
            }
            String userName = textFieldNewUser.getText().trim();
            Vector v = new Vector();
            v.add("用户：" + userName);
            try {
                outputStream.writeObject(v);
                outputStream.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            textFieldNewUser.setEnabled(false);
            loginFlag = true;
        });
        button1.setText("登  录");
        panel1.add(button1);

        final JButton button2 = new JButton();
        button2.addActionListener(e -> {
            String exitUser = textFieldNewUser.getText().trim();
            Vector v = new Vector();
            v.add("退出：" + exitUser);
            try {
                outputStream.writeObject(v);
                outputStream.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.exit(0);
        });
        button2.setText("退  出");
        panel1.add(button2);

        if (SystemTray.isSupported()) {
//            URL url = ResourceUtil.getResource("1.png", null);
            URL resource = getClass().getResource("1.PNG");
            ImageIcon icon = new ImageIcon(resource);
            Image image = icon.getImage();
            TrayIcon trayIcon = new TrayIcon(image);
            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        showFrame();
                    }
                }
            });
            trayIcon.setToolTip("系统托盘");
            PopupMenu popupMenu = new PopupMenu();
            MenuItem exit = new MenuItem("退出");
            exit.addActionListener(e -> {
                String exitUser = textFieldNewUser.getText().trim();
                Vector v = new Vector();
                v.add("退出：" + exitUser);
                try {
                    outputStream.writeObject(v);
                    outputStream.flush();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                System.exit(0);
            });
            popupMenu.add(exit);
            trayIcon.setPopupMenu(popupMenu);
            SystemTray systemTray = SystemTray.getSystemTray();
            try {
                systemTray.add(trayIcon);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public void showFrame() {
        this.setVisible(true);
        this.setState(Frame.NORMAL);
    }


    private void send() {
        System.out.println("send"+loginFlag);
        if (!loginFlag) {
            JOptionPane.showMessageDialog(null, "请先登录");
            return;
        }
        String sendUserName = textFieldNewUser.getText().trim();
        String info = textFieldSend.getText();
        if ("".equals(info)) {
            return;
        }
        Vector<String> vector = new Vector<>();
        Object[] receiveUserNames = userList.getSelectedValues();
        if (receiveUserNames.length <= 0) {
            return;
        }

        for (int i = 0; i < receiveUserNames.length; i++) {
            String msg = sendUserName + "：发送给：" + receiveUserNames[i] + "：的信息是：" + info;
            vector.add(msg);
        }
        try {
            outputStream.writeObject(vector);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DateFormat dateInstance = DateFormat.getDateInstance();
        String dateString = dateInstance.format(new Date());
        dateInstance = DateFormat.getTimeInstance(DateFormat.MEDIUM);
        String timeString = dateInstance.format(new Date());
        String sendUser = textFieldNewUser.getText().trim();
        String receiveInfo = textFieldSend.getText().trim();
        textAreaInfo.append(" " + sendUser + " " + dateString + " " + timeString + "\n " + receiveInfo + "\n");
        textFieldSend.setText(null);
        textAreaInfo.setSelectionStart(textAreaInfo.getText().length() - 1);
        textAreaInfo.setSelectionEnd(textAreaInfo.getText().length());
        textFieldSend.requestFocus();
    }

    public void createClientSocket() {
        try {
            socket = new Socket("127.0.0.1", 9527);
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() {
                    try {
                        System.out.println(SwingUtilities.isEventDispatchThread());
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        DefaultComboBoxModel model = (DefaultComboBoxModel) userList.getModel();
                        while (true) {
                            String info = reader.readLine().trim();

                            if (!info.startsWith("MSG：")) {
                                if (info.startsWith("退出")) {
                                    model.removeElement(info.substring(3));
                                } else {
                                    boolean itemFlag = false;
                                    for (int i = 0; i < model.getSize(); i++) {
                                        if (info.equals(model.getElementAt(i))) {
                                            itemFlag = true;
                                            break;
                                        }
                                    }
                                    if (!itemFlag) {
                                        model.addElement(info);
                                    }
                                }
                            } else {
                                System.out.println("info:"+info);
                                DateFormat dateInstance = DateFormat.getDateInstance();
                                String dateString = dateInstance.format(new Date());
                                dateInstance = DateFormat.getTimeInstance(DateFormat.MEDIUM);
                                String timeString = dateInstance.format(new Date());
                                String sendUser = info.substring(4, info.indexOf("：发送给："));
                                String receiveInfo = info.substring(info.indexOf("：的信息是：") + 6);
                                textAreaInfo.append(" " + sendUser + " " + dateString + " " + timeString + "\n " + receiveInfo + "\n");
                                textFieldSend.setText(null);
                                textAreaInfo.setSelectionStart(textAreaInfo.getText().length() - 1);
                                textAreaInfo.setSelectionEnd(textAreaInfo.getText().length());
                                textFieldSend.requestFocus();
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            };
            worker.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}